package threads;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Level;

import model.Settings;
import util.LoggingUtils;

public class LogRemover implements Runnable {

	private int ageInDays;
	private int interval;

	public LogRemover(int ageInDays, int interval) {
		this.ageInDays = ageInDays;
		this.interval = interval;
	}
	
	@Override
	public void run() {
		while(true) {
			deleteOldLogFiles(ageInDays);
			try {
				Thread.sleep(interval);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				String classMethod = "threads.LogRemover in .run()";
				LoggingUtils.logStart(classMethod);
				LoggingUtils.log(Level.SEVERE,e.getMessage() + classMethod,e);
			}
		}
	}
	
	public void generateFile() throws IOException {
		File newFile = new File(Settings.LOG_DIRECTORY+File.separator+System.currentTimeMillis()+".txt");
		newFile.createNewFile();
	}
	
	public void deleteOldLogFiles(int ageInDays) {
		Calendar limit = Calendar.getInstance();
		limit.add(limit.DAY_OF_MONTH, -ageInDays);
		
		Calendar fileCreationDate = Calendar.getInstance();
		File logDirectory = new File(Settings.LOG_DIRECTORY);
		for(File logFile : logDirectory.listFiles()) {
			// check the modified date, delete if older than age
			long lastModified = logFile.lastModified();
			fileCreationDate.setTimeInMillis(lastModified);
			if(fileCreationDate.before(limit)) {
				logFile.delete();
				System.out.println("DELETING LOG");
			}
		}
	}
	
	public static void main(String[] args) {
		Thread logRemoverThread = new Thread(new LogRemover(5, 1000*60*60*24));
		logRemoverThread.setName("Log Remover Thread.");
		logRemoverThread.start();
	}
}
